package quantum2.draw;

import quantum2.graph.StatResult;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MainFrame extends JFrame {

    private final MainPanel panel = new MainPanel();
    private final ResultPanel rpanel = new ResultPanel();

    private Running running = null;
    private final Timer timer = new Timer(200, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            showRunning();
        }
    });
    private final AbstractAction runAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            runModel();
        }
    };
    private final AbstractAction pauseAction = new AbstractAction("Pause") {
        public void actionPerformed(ActionEvent e) {
            pauseModel();
        }
    };

    public MainFrame() {
        super("Complex graph");
        add(panel, BorderLayout.WEST);
        add(rpanel, BorderLayout.CENTER);

        JToolBar bar = new JToolBar();
        bar.add(runAction);
        bar.add(pauseAction);
        stopModel();
        add(bar, BorderLayout.NORTH);

        try {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        } catch (Exception ex) {
            // ignore
        }
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new MainFrame();
    }

    private void runModel() {
        if (running == null) {
            running = Running.getRunning(panel);
            if (running == null)
                return;
            runAction.putValue(AbstractAction.NAME, "Stop");
            pauseAction.setEnabled(true);
            timer.setDelay(200);
            timer.setInitialDelay(0);
            timer.start();
            running.start();
        } else {
            stopModel();
        }
    }

    private void stopModel() {
        runAction.putValue(AbstractAction.NAME, "Run");
        pauseAction.putValue(AbstractAction.NAME, "Pause");
        pauseAction.setEnabled(false);
        timer.stop();
        if (running != null) {
            running.stop();
        }
        rpanel.clearStat();
        running = null;
    }

    private void pauseModel() {
        if (timer.isRunning()) {
            pauseAction.putValue(AbstractAction.NAME, "Resume");
            timer.stop();
        } else {
            pauseAction.putValue(AbstractAction.NAME, "Pause");
            timer.start();
        }
    }

    private void showRunning() {
        if (running != null) {
            StatResult result = running.getStat();
            rpanel.setStat(result);
        } else {
            timer.stop();
        }
    }
}
